package cn.edu.zust.remoteemailservice.controller;

import Email.Dto.RemoteEmailDto;
import jakarta.mail.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/remoteEmail")
public class EmailController {

    /**
     * 注入邮件工具类
     */
    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Value("${spring.mail.username}")
    private String sendMailer;

    @PostMapping("sendEmail")
    public void sendEmail(@RequestBody RemoteEmailDto remoteEmailDto) {
        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(),true);
            //邮件发信人
            mimeMessageHelper.setFrom(sendMailer);
            //邮件收信人
            mimeMessageHelper.setTo(remoteEmailDto.getReceive());
            //邮件主题
            mimeMessageHelper.setSubject(remoteEmailDto.getTitle());
            //邮件内容
            mimeMessageHelper.setText(remoteEmailDto.getText());
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());
            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            System.out.println("发送邮件成功：" +sendMailer+"===>"+remoteEmailDto.getReceive());

        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送邮件失败："+e.getMessage());
        }
    }
}

